package cn.stylefeng.guns.modular.rest.transport;

import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.MapUtils;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicDriverParam;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.hx.storage.controller.HxStorageRecordController;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoreReturnsRegisterParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxXhTransportResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoreReturnsRegisterService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.transport.model.params.TransportRegistrationSigninParam;
import cn.stylefeng.guns.modular.transport.model.result.TransportRegistrationSigninResult;
import cn.stylefeng.guns.modular.transport.service.TransportRegistrationSigninService;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import cn.stylefeng.guns.modular.transport.entity.TransportRegistrationSignin;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Controller
@RequestMapping("/rest/temporary")
public class restTemporaryController {

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private TransportRegistrationSigninService transportRegistrationSigninService;

    /**
     * 临时工签到
     */
    @RequestMapping("/signincode")
    @ResponseBody
    public ResponseData signincode(TransportRegistrationSigninParam transportRegistrationSigninParam,String longitude,String latitude,String currentAddress) {

        if(ToolUtil.isEmpty(transportRegistrationSigninParam.getTemporaryName())) {
            return ResponseData.error("请填写姓名");
        }
        if(ToolUtil.isEmpty(transportRegistrationSigninParam.getTel())) {
            return ResponseData.error("请填写手机号");
        }
        if (ToolUtil.isEmpty(transportRegistrationSigninParam.getIdcard())){
            return ResponseData.error("请输入身份证号码");
        }
        if(ToolUtil.isEmpty(transportRegistrationSigninParam.getLaborServices())) {
            return ResponseData.error("请填写劳务公司");
        }
        BasicWarehouse byId = basicWarehouseService.getById(transportRegistrationSigninParam.getWarehouseId());
        BasicOperate operate = basicOperateService.getById(byId.getWarehouseOperateId());
        transportRegistrationSigninParam.setStartTime(DateUtil.getDateS());
        transportRegistrationSigninParam.setV1(currentAddress);
        TransportRegistrationSigninResult ch = transportRegistrationSigninService.find(transportRegistrationSigninParam);
        if (ch == null) {
        	if(ToolUtil.isNotEmpty(longitude) && ToolUtil.isNotEmpty(latitude)) {
        		if (ToolUtil.isNotEmpty(byId.getLongitude()) && ToolUtil.isNotEmpty(byId.getLatitude())) {
        			double a = MapUtils.GetDistance(Double.parseDouble(byId.getLongitude()), Double.parseDouble(byId.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
        			double radius = 1500;
        			if (radius < a) {
        				return ResponseData.error("不在签到范围内，无法签到");
        			}
        		} else {
        			return ResponseData.error("签到地址经纬度不存在，请联系管理员");
        		}
        	}
            transportRegistrationSigninParam.setDeptId(operate.getDeptId());
            transportRegistrationSigninParam.setDeliverId(operate.getDeliverId());
            transportRegistrationSigninService.add(transportRegistrationSigninParam);
        } else  {
            if (ch.getEndTime()==null){
                return ResponseData.error("您已经签到过");
            }else if (ch.getTel().equals(transportRegistrationSigninParam.getTel())&&ch.getStartTime()!=null){
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date endTime = sdf.parse(ch.getEndTime());
                    Date startTime = new Date();
                    long diff = startTime.getTime() - endTime.getTime(); // 两个时间戳的差值（毫秒）
                    long diffMinutes = diff / (60 * 1000); // 差值转换为分钟
                    if (diffMinutes < 10) {
                        // 差值小于十分钟的情况
                        return ResponseData.error("签退10分钟后才可再次签到！！！");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                TransportRegistrationSigninParam newSigninParam = new TransportRegistrationSigninParam();
                BeanUtils.copyProperties(transportRegistrationSigninParam, newSigninParam);
                newSigninParam.setStartTime(DateUtil.getDateS());
                newSigninParam.setV1(currentAddress);
                newSigninParam.setDeptId(operate.getDeptId());
                newSigninParam.setDeliverId(operate.getDeliverId());
                transportRegistrationSigninService.add(newSigninParam);
                return ResponseData.success("签到成功");
            }
        }
        return ResponseData.success();
    }

    /**
     * 临时工签退
     */
    @RequestMapping("/signoutcode")
    @ResponseBody
    public ResponseData signoutcode(TransportRegistrationSigninParam transportRegistrationSigninParam,String longitude,String latitude,String currentAddress) {
        if (ToolUtil.isEmpty(transportRegistrationSigninParam.getTemporaryName())) {
            return ResponseData.error("请填写姓名");
        }
        if (ToolUtil.isEmpty(transportRegistrationSigninParam.getTel())) {
            return ResponseData.error("请填写手机号");
        }
        if (ToolUtil.isEmpty(transportRegistrationSigninParam.getIdcard())){
            return ResponseData.error("请输入身份证号码");
        }
        if (ToolUtil.isEmpty(transportRegistrationSigninParam.getLaborServices())) {
            return ResponseData.error("请填写劳务公司");
        }
        TransportRegistrationSigninResult ch = transportRegistrationSigninService.find(transportRegistrationSigninParam);
        if (ch != null) {
            if (ToolUtil.isNotEmpty(ch.getStartTime()) && ToolUtil.isNotEmpty(ch.getEndTime())) {
                return ResponseData.error("请先签到，再签退");
            }
            if (ToolUtil.isNotEmpty(ch.getEndTime())) {
                TransportRegistrationSigninParam newSignoutParam = new TransportRegistrationSigninParam();
                BeanUtils.copyProperties(transportRegistrationSigninParam, newSignoutParam);
                newSignoutParam.setEndTime(DateUtil.getDateS());
                newSignoutParam.setV2(currentAddress);
                transportRegistrationSigninService.add(newSignoutParam);
                return ResponseData.success("签退成功");
            } else {
                BasicWarehouse byId = basicWarehouseService.getById(transportRegistrationSigninParam.getWarehouseId());
                if(ToolUtil.isNotEmpty(longitude) && ToolUtil.isNotEmpty(latitude)) {
                    if (ToolUtil.isNotEmpty(byId.getLongitude()) && ToolUtil.isNotEmpty(byId.getLatitude())) {
                        double a = MapUtils.GetDistance(Double.parseDouble(byId.getLongitude()), Double.parseDouble(byId.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
                        double radius = 1500;
                        if (radius < a) {
                            return ResponseData.error("不在签到范围内，无法签到");
                        }
                    } else {
                        return ResponseData.error("签到地址经纬度不存在，请联系管理员");
                    }
                }
                transportRegistrationSigninParam.setEndTime(DateUtil.getDateS());
                transportRegistrationSigninParam.setV2(currentAddress);
                transportRegistrationSigninParam.setId(ch.getId());
                transportRegistrationSigninService.update(transportRegistrationSigninParam);
            }
        } else {
            return ResponseData.error("请先签到，再签退");
        }
        return ResponseData.success();
    }
    private Lock lock = new ReentrantLock();

    @Autowired
    private HxStoreReturnsRegisterService hxStoreReturnsRegisterService;
    /**
     * 门店退货登记
     */
    @RequestMapping("/storeReturns")
    @ResponseBody
    public ResponseData storeReturns(HxStoreReturnsRegisterParam hxStoreReturnsRegisterParam) {
        if (ToolUtil.isEmpty(hxStoreReturnsRegisterParam.getUnitName())) {
            return ResponseData.error("请填写申请门店");
        }
        if (ToolUtil.isEmpty(hxStoreReturnsRegisterParam.getGoodsName())) {
            return ResponseData.error("请填写退货品名");
        }
        if (ToolUtil.isEmpty(hxStoreReturnsRegisterParam.getRefundNum())){
            return ResponseData.error("请输入退货箱数");
        }
        if (ToolUtil.isEmpty(hxStoreReturnsRegisterParam.getRefundFeedback())) {
            return ResponseData.error("请填写退货照片反馈");
        }
        if (ToolUtil.isEmpty(hxStoreReturnsRegisterParam.getCarryDate())) {
            return ResponseData.error("请填写提走日期");
        }
        lock.lock();//获取锁
        try {
            HxStoreReturnsRegisterParam StoreReturnsRegister = new HxStoreReturnsRegisterParam();
            StoreReturnsRegister.setUnitName(hxStoreReturnsRegisterParam.getUnitName());
            StoreReturnsRegister.setGoodsName(hxStoreReturnsRegisterParam.getGoodsName());
            StoreReturnsRegister.setRefundNum(hxStoreReturnsRegisterParam.getRefundNum());
            StoreReturnsRegister.setRefundFeedback(hxStoreReturnsRegisterParam.getRefundFeedback());
            StoreReturnsRegister.setCarryDate(hxStoreReturnsRegisterParam.getCarryDate());
            hxStoreReturnsRegisterService.add(StoreReturnsRegister);
            return ResponseData.success("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return ResponseData.success();
    }
    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 上传退货照片
     * @param file
     * @return
     */
    @RequestMapping("/uploadsnew1")
    @ResponseBody
    public ResponseData uploadsnew1(@RequestParam("file") MultipartFile file, Integer id,  HxStoreReturnsRegisterParam hxStoreReturnsRegisterParam) {
        String fileId = this.fileInfoService.uploadFileCar(file);

        hxStoreReturnsRegisterParam.setId(id);
        hxStoreReturnsRegisterParam.setRefundPhotoId(fileId);
        hxStoreReturnsRegisterService.update(hxStoreReturnsRegisterParam);
        return ResponseData.success(fileId);
    }
}
